package com.xuchao.http;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @Author xuchao
 * @Date:2024/1/18 17:31
 * @description
 * @Version 1.0
 */
@Slf4j
@ChannelHandler.Sharable
public class HttpDecoder extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        FullHttpRequest fullHttpRequest = (FullHttpRequest) msg;
        String req = fullHttpRequest.content().toString(CharsetUtil.UTF_8);
        String uri = fullHttpRequest.uri();
        String length = fullHttpRequest.headers().get("Content-Length");
        String method = fullHttpRequest.method().toString();
        log.info("uri:{},method:{},长度：{}", uri, method, length);
        JSONObject jsonObject = new JSONObject(req);
        log.info("报文体:{}", jsonObject);
        send(ctx, jsonObject);
        super.channelRead(ctx, jsonObject);
    }

    private void send(ChannelHandlerContext ctx, JSONObject msg) {
        String str = JSONUtil.toJsonStr(msg);
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        ByteBuf buf = ctx.alloc().buffer();
        buf.writeBytes(bytes);
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, bytes.length);
        response.headers().set(HttpHeaderNames.CONNECTION, "keep-alive");
        ctx.writeAndFlush(response);
    }
}
